package com.todod.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.todod.common.util.FileUtil;
import com.todod.dto.BaseFileDto;
import com.todod.entity.ResultData;
import com.todod.exception.CustomException;
import com.todod.mapper.BaseFileMapper;
import com.todod.model.BaseFile;
import com.todod.service.IBaseFileService;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author gmm
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/baseFile")
public class BaseFileController {

	@Autowired
	private IBaseFileService ibaseFileService;
	@Autowired
	private BaseFileMapper baseFileMapper;

	/**
	 * 上传
	 * 
	 * @param _userId
	 * @param request
	 * @param linkId
	 * @param filetype
	 * @return
	 */
	@PostMapping("/upload")
	public ResultData upload(@RequestAttribute Long _userId, HttpServletRequest request, String linkId,
			String filetype) {
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, Object> data = ibaseFileService.saveUploadFile(_userId, request, linkId, filetype);
			return ResultData.success("ok", data);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	@PostMapping("/upload1")
	public ResultData upload(@RequestAttribute Long _userId, HttpServletRequest request, HttpServletResponse response,
			String linkId, String filetype) {
		try {
			request.setCharacterEncoding("utf-8");
			String path = ibaseFileService.saveUploadFile1(_userId, request, linkId, filetype);
			return ResultData.success("ok", path);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}

	}

	/**
	 * @Title: getFileList
	 * @Description:获取专家库-附件信息
	 * @author dyl
	 * @date 2020-10-28
	 * @param
	 * @return
	 */
	@GetMapping("/getFileList")
	public ResultData getFileList(String linkId, String filetype) {
		if (filetype == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}
		List<BaseFileDto> baseFileDtos = ibaseFileService.getFileList(linkId, filetype);

		return ResultData.success("ok", baseFileDtos);
	}

	@PostMapping("/downloadById/flow")
	public String downloadById(HttpServletRequest request, HttpServletResponse response, Long id) throws Exception {
		BaseFile byId = ibaseFileService.getById(id);
		File file = new File(byId.getAbstractPath());
		if (!file.isFile())
			throw new CustomException("文件丢失");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-Disposition",
				"attachment; filename=" + URLEncoder.encode(byId.getOriginalName(), "UTF-8"));
		response.setHeader("Content-Type", "text/xml;charset=utf-8");

		// 通过流把文件内容写入到客户端
		InputStream fis = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
//		         byte[] buffer = new byte[fis.available()];
//		         fis.read(buffer);
		FileCopyUtils.copy(fis, response.getOutputStream());
		fis.close();
		return "";
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteFile")
	public ResultData deleteData(Long id) {
		ibaseFileService.deleteData(id);
		return ResultData.success("ok");
	}

	/**
	 * 关闭新增或编辑页面 清楚map和文件
	 *
	 * @return
	 */
	@PostMapping("/close")
	public ResultData close(@RequestAttribute Long _userId) throws Exception {
		FileUtil.deletebyCondition(_userId);
		return ResultData.success();
	}

	/**
	 * 清理单个上传的文件
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/clean")
	public ResultData clean(@RequestBody Object file) throws Exception {
		Map<String, String> filemap = (Map) file;

		if (filemap.get("name") != null && !filemap.get("name").equals("")) {
			String filename = filemap.get("name");
			Map<String, BaseFile> transfor = FileUtil.getBasefileMap();
			BaseFile baseFile = transfor.get(filename);
//			System.out.println(baseFile.toString());
			if (baseFile != null) {
				String abstractPath = baseFile.getAbstractPath();
				System.out.println(abstractPath);
				File filed = new File(abstractPath);
				if (filed.exists()) {
					boolean delete = filed.delete();
					transfor.remove(filename);
				}
				// 重新计算排序
				int i = 1;
				for (String key : transfor.keySet()) {
					BaseFile baseFile1 = transfor.get(key);
					baseFile.setSortNum(i++);
				}
			}

		} else {
			String id = filemap.get("id");
			Long fileid = Long.valueOf(id);
			BaseFile file1 = baseFileMapper.selectById(fileid);
			String abstractPath = file1.getAbstractPath();
			File file2 = new File(abstractPath);
			if (file2.isFile()) {
				file2.delete();
			}
			baseFileMapper.deleteById(Long.valueOf(file1.getId()));
		}
		return ResultData.success();
	}

}
